package com;

import java.util.ArrayList;

import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleWeightedGraph;

public class TopLevel {
	
	/*This method is where all the different modules of the applet are called in order.*/
	
	//ArrayList of the alibi checker nodes. 
	static ArrayList<Node> newNodes = new ArrayList<Node>();
	//A graph containing the Cambridge XML data plus the alibi checker nodes.
	static SimpleWeightedGraph<Node, DefaultWeightedEdge> newgraph;
	//A graph containing only the alibi checker nodes for TSP.
	static SimpleWeightedGraph<Node, DefaultWeightedEdge> locationsGraph;
	//ArrayList of markers obtained from Javascript.
	static ArrayList<Marker> markers = AlibiTesterApplet.markers;
	
	static long startTime, endTime;

	public static int doTheWork() {
		 //Initialise min_dist.
		 double min_dist = 0.0;
		 
		 //get locations from GUI (as pairs of lat and lon) and convert them to nodes.
		 newNodes = convertToNodes(markers);
		 
		 //adds alibi checker nodes to Cambridge graph. 
		 newgraph = AddLocationsToGraph.add(newNodes, AlibiTesterApplet.oldgraph);
	
		 //creates a new graph to run TSP in.
		 locationsGraph = CreateTSGraph.create(newgraph, newNodes);
		 
		 //run TS on locations graph to find the distance of the shortest route. 
		 startTime = System.nanoTime();
		 min_dist = TSGreedy.compute(locationsGraph);
		 endTime = System.nanoTime();
		  
		 //convert distance to time according to the mode of transport selected in GUI.
		 double min_timeDouble = ReturnTimeFromType.getTime(min_dist);
		 
		 //round the min. time to the closest integer and return it.	
		 int minTimeInt = (int) Math.rint(min_timeDouble);
		 
	return minTimeInt;
		 
	}

	
	public static ArrayList<Node> convertToNodes(ArrayList<Marker> markers) {
	/*this method turns the Markers into Nodes and assigns them id values 
	  that dont clash with the ids of the nodes from the XML file.*/
		int idNum = 0;
		for (Marker mrk : markers) {
			idNum++;
			Node node = new Node();
			node.lat = mrk.lat;
			node.lon = mrk.lon;
			node.id = Integer.toString(idNum);
			newNodes.add(node);
		}
		//reset the starting id number back to zero.
		idNum = 0;
	
	return newNodes;
	}
	 
}
